package com.chdwmp.product.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.chdwmp.product.bean.PageResult;
import com.chdwmp.product.bean.backend.*;
import com.chdwmp.product.bean.params.AgentListSearch;
import com.chdwmp.product.bean.pay.OrderInfoBo;
import com.chdwmp.product.constant.CommonConstants;
import com.chdwmp.product.constant.Status;
import com.chdwmp.product.exception.CommonException;
import com.chdwmp.product.mapper.AgentMapper;
import com.chdwmp.product.mapper.TRegisterPayMapper;
import com.chdwmp.product.service.AgentService;
import com.chdwmp.product.utils.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Auther: LLL
 * @Date: 2021/5/9 09:10
 * @Description:
 */
@Service
public class AgentServiceImpl implements AgentService {

    @Autowired
    AgentMapper agentMapper;
    @Autowired
    TRegisterPayMapper registerPayMapper;

    @Override
    public void saveOrUpdateAgent(AgentVo agentVo) {
        if(null != agentVo.getId()){
            //更新
            agentMapper.updateAgent(agentVo);
        }else{
            //新增
            agentMapper.insertAgent(agentVo);
        }
    }

    @Override
    public void deleteAgent(String id) {
        if(StrUtil.isEmpty(id))
            throw new CommonException(Status.MISS_REQUIRED_PARAMETER);
        agentMapper.deleteAgent(id);
    }

    @Override
    public PageResult getAgentList(AgentListSearch search) {

        int rows = search.getPageSize();
        if (rows == 0) {
            rows = CommonConstants.PAGE_SIZE;
        }
        int start_rows = search.getPage() * rows;
        search.setPage(start_rows);
        search.setPageSize(rows);

        int count  = agentMapper.queryTotalCount(search);

        if (count == 0){
            return new PageResult<>(count,start_rows, Collections.emptyList());
        }

        List<AgentVo> list  = agentMapper.queryAgentList(search);
        if(null != list && list.size() > 0){
            for (AgentVo agentListVo : list) {
                StringBuilder str = new StringBuilder();
                //查询购买的产品
                List<AgentBuyProductVo> productNames =  agentMapper.queryAgentBuyProduct(agentListVo.getAgentName());
                if (ObjectUtil.isNotEmpty(productNames)){
                    for (AgentBuyProductVo productVo : productNames) {
                        str = str.append(productVo.getProduct_name()).append(":").append(productVo.getCount()).append("\n");
                    }
                    agentListVo.setBuyProductsStr(str.toString());
                }
                //查询供应商已经激活的产品数量 产品ID 是一个的  正常的
                int agent_buy_count  = agentMapper.queryAgentBuyProductCount(agentListVo.getAgentName());
                int agent_buy_count_list = agentMapper.queryAgentBuyProdutCoutList(agentListVo.getAgentName());
                //已激活的数量
                agentListVo.setActiveCount(agent_buy_count + agent_buy_count_list);
                //未激活的数量
                agentListVo.setInactiveCount(agentListVo.getBuyCount());
                //总数
                agentListVo.setBuyCount(agentListVo.getActiveCount() + agentListVo.getBuyCount());
            }
        }
        return new PageResult<>(count,start_rows,null == list?new ArrayList<>():list);
    }

    @Override
    @Transactional
    public AgentVo addAgentForApp(AgentVo agentVo) {
        int count = agentMapper.queryAgentIsExits(agentVo.getAgentName(),agentVo.getImei());
        if(count > 0){
            String createTime = agentMapper.queryAgentBuyProductTime(agentVo.getAgentName(),agentVo.getImei());
            //查询购买的产品
            List<String> productNames =  agentMapper.queryAgentBuyProductIds(agentVo.getAgentName());
            agentVo.setBuyProducts(productNames);
            agentVo.setCreateTime(createTime);
            return agentVo;
        }else{
            //新增供应商，看是否需要赠送产品
            int imei_count = agentMapper.queryImeiIsExits(agentVo.getImei());
            int agent_count = agentMapper.queryAgentCount(agentVo.getAgentName());
            if(imei_count == 0 && agent_count ==0 ){
                agentMapper.insertAgent(agentVo);
                agentVo.setCreateTime(LocalDateTime.now().toString());
                if(null != agentVo.getProductIds() && agentVo.getProductIds().size() > 0){
                    for (Integer productId : agentVo.getProductIds()) {
                        Integer count_realtion = registerPayMapper.queryRealtionIsExits(agentVo.getId(),String.valueOf(productId));
                        if(null != count_realtion && count_realtion > 0){
                            //只更新数量
                            registerPayMapper.updateReationCount(agentVo.getId(),String.valueOf(productId),agentVo.getProductIds().size());
                        }else{
                            agentMapper.addAgentProductRealtion(productId,agentVo.getId(),agentVo.getProductIds().size());
                        }
                    }
                    //更新赠送数量到 供应商表中
                    agentMapper.updateAgentGiveCount(agentVo.getId(),agentVo.getProductIds().size());
                }
            }


            return agentVo;
        }
    }

    @Override
    public PageResult getAgentBuyProducts(AgentListSearch search) {

        int rows = search.getPageSize();
        if (rows == 0) {
            rows = CommonConstants.PAGE_SIZE;
        }
        int start_rows = search.getPage() * rows;
        search.setPage(start_rows);
        search.setPageSize(rows);

        int count  = agentMapper.queryTotalBuyCount(search);

        if (count == 0){
            return new PageResult<>(count,start_rows, Collections.emptyList());
        }

        List<AgentListVo> list = agentMapper.queryAgentBuyProducts(search);
        if(null != list && list.size() > 0){
            for (AgentListVo agentListVo : list) {
                //查询购买的产品
//                List<String> productNames =  agentMapper.queryAgentBuyProduct(agentListVo.getAgentName());
//                agentListVo.setProductNames(productNames);
            }
        }
        return new PageResult(count,start_rows,list);
    }

    @Override
    public AgentVo getAgentInfo(String imei) {
        return agentMapper.queryAgentInfoByImei(imei);
    }

    @Override
    public PageResult getProductAgentStatistics(ProductAgentSearchVo productAgentSearchVo) {
        int rows = productAgentSearchVo.getPageSize();
        if (rows == 0) {
            rows = CommonConstants.PAGE_SIZE;
        }
        int start_rows = productAgentSearchVo.getPage() * rows;
        productAgentSearchVo.setPage(start_rows);
        productAgentSearchVo.setPageSize(rows);

        int count  =  agentMapper.queryAgentStatisticCount(productAgentSearchVo);
        if (count == 0){
            return new PageResult<>(count,start_rows, Collections.emptyList());
        }
        List<ProductStatisticsVo> list = agentMapper.queryProductAgentStatisticList(productAgentSearchVo);
        if(null != list && !list.isEmpty()){
            for (ProductStatisticsVo productStatisticsVo : list) {

                productAgentSearchVo.setAgentId(String.valueOf(productStatisticsVo.getAgentId()));
                List<AgentBuyProductVo> buy_list = agentMapper.queryAgentBuyList(productAgentSearchVo);
                if(null != buy_list){
                    int totalCount = 0;
                    for (AgentBuyProductVo agentBuyProductVo : buy_list) {
                        totalCount +=agentBuyProductVo.getCount();
                    }
                    productStatisticsVo.setTotalCount(totalCount);
                }
                productStatisticsVo.setList(buy_list);
            }

        }
        return new PageResult(count,start_rows,list.stream().sorted(Comparator.comparing(ProductStatisticsVo::getTotalCount).reversed()).collect(Collectors.toList()));
    }


}
